package org.lex.tinyscript.command;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.lex.tinyscript.JavaLauncher;
import org.lex.tinyscript.TinyScriptException;
import org.lex.tinyscript.utils.Loggers;

public class JavaCommand extends AbstractScriptCommand {
	private File file = null;

	public JavaCommand() {
	}

	public void excute() throws TinyScriptException {
		Loggers.getLogger().info("executing java " + this.file);
		try {
			Properties props = new Properties();
			props.load(new FileInputStream(file));
			new JavaLauncher(props).getProcessBuilder().start();
		} catch (FileNotFoundException e) {
			String err = "launch properties file not exists: " + this.file;
			Loggers.getLogger().severe(err);
			throw new TinyScriptException(err, e);
		} catch (IOException e) {
			String err = "launch java process failed with properties="
					+ this.file;
			Loggers.getLogger().severe(err);
			throw new TinyScriptException(err, e);
		}
	}

	public String getCommand() {
		return "java";
	}

	public void setArguments(String... arguments) throws TinyScriptException {
		this.checkArgumentsLength(1, arguments);
		this.file = new File(arguments[0]);
	}

	public JavaCommand clone() throws CloneNotSupportedException {
		return (JavaCommand) super.clone();
	}
}
